const querystring = require("querystring");

const writeTextResponse = function(response,text){
	response.writeHead(200,{
        "content-type":"text/plain; charset=UTF-8"
    });
    response.write(text);
    response.end();
};
function TypeParamsHandler(){
    this.getParameter = function(request,key,defaultValue){
        return defaultValue;
    }
}
const _getTypeParamsHandler = new TypeParamsHandler();

_getTypeParamsHandler.getParameter = function(request,key,defaultValue){
     var retStr = defaultValue;
     let rps = request.url.split("?");
     var url = "";
     if(rps && rps.length > 1){
            url =  rps[1].split("#")[0];
     }
     const reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
     var r =url.match(reg);
     if (r != null){
         var rev = r[2];
         if(rev){
            retStr = unescape(rev);
         }
     } ; 
     return retStr;
};

const _postTypeParamsHandler = new TypeParamsHandler();
_postTypeParamsHandler.getParameter=  function(request,key,defaultValue){
    if(request._mvcParams && request._mvcParams.postParamsMap){
        if(request._mvcParams.postParamsMap[key]){
            return request._mvcParams.postParamsMap[key];
        }else{
            return defaultValue;
        }
    }
    return defaultValue;
};



const paramsHandlerWare={
    "GET":_getTypeParamsHandler,
    "POST":_postTypeParamsHandler
};

function generateTypeParamsHandler(type){
    if(!type) return null;
    return paramsHandlerWare[type.toUpperCase()];
}
const writeJSONResponse = function(response,code,obj){
    var retObj = {};
    retObj.code = code;
    retObj.data = obj;
    writeTextResponse(response,JSON.stringify(retObj));
};

const ActionEntity = function(actionStr,actionType){
   this.actionStr = actionStr;
   this.actionType = actionType; 
};
const parseActionEntity = function(mappingUrl,requestUrl){
    let tds = requestUrl;
    if(tds.indexOf("?") != -1){
        tds = tds.split("?")[0];
    }
    if(tds.indexOf(".") !=-1){
        var tdss = tds.split(".")
        return new ActionEntity(tdss[0],tdss[1]);
    }else{
        return new ActionEntity(tds,null);
    }
    
}

function getParameter(request,key,defaultValue){
    //
    var typeHandler = generateTypeParamsHandler(request.method);
    if(!typeHandler){
        // 不支持的类型
        return defaultValue;
    }
    return typeHandler.getParameter(request,key,defaultValue);
    
}

function initRequest(request){
    return new Promise(function(resolve, reject){
        if(request.method){
            if("POST" == request.method.toUpperCase()){
                var str="";
                request.on("data",function(chunk){
                    str +=chunk;
                });
                request.on("end", function(){
                    var qobj = querystring.parse(str);
                    
                    var rmap = qobj || {};
                    request._mvcParams={
                        "postParamsMap":rmap,
                        "requestStr":str
                    };
                    resolve(true) ;
                });
            }else{
                resolve(true) ;
            }
            
        }else{
            resolve(true) ;
        }
        
    });
    
}

function getRequestUrl(request){
    return request.url;
}


module.exports = {
    writeTextResponse:writeTextResponse,
    writeJSONResponse:writeJSONResponse,
    parseActionEntity:parseActionEntity,
    getRequestUrl:getRequestUrl,
    getParameter:getParameter,
    initRequest:initRequest
};